package com.micai.boss.base.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eetrust.label.LabelOperator;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhaoxinguo
 * @Date 2022-04-26 19:23
 * @ClassName HttpUtils
 * @Description TODO
 */
public class HttpUtils {

    public static JSONObject httpPost(String url, Object data) {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(20000).setConnectTimeout(20000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json");

        try {
            StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), ContentType.APPLICATION_JSON);
            httpPost.setEntity(requestEntity);
            response = httpClient.execute(httpPost, new BasicHttpContext());
            if (response.getStatusLine().getStatusCode() != 200) {
                //System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                JSONObject result = JSON.parseObject(resultStr);
                //LOG.error("ofd转换result："+result);
                if (result.getInteger("returncode") == 200) {
                    //result.remove("code");
                    //result.remove("msg");
                    return result;
                } else {
                    //System.out.println("request url=" + url + ",return value=");
                    //System.out.println(resultStr);
                    int code = result.getInteger("returncode");
                    String msg = result.getString("returnmsg");
                }
            }
        } catch (IOException e) {
            //e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 将文件转换成byte数组
     *
     * @param tradeFile
     * @return
     */
    public static byte[] File2byte(File tradeFile) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static void main(String[] args) throws Exception {
        LabelOperator labelOperator = new LabelOperator("172.18.22.121", 8060);
        String servicePath = "http://172.18.20.221:9203/gsdk-service" + "/v1/ofd/byteStream";
        Map<String, Object> param = new HashMap<String, Object>();
        try {
            /**
             * 1、对在线编辑产生的doc文件先脱标
             * 2、脱标以后的白文件调用文件转换服务，由doc转换成ofd
             * 3、转换以后，再加标，上传
             */
            String oldFileName = "1650966931194.doc";
            String newFileName = oldFileName.substring(0, oldFileName.lastIndexOf("."));
            String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
            String filePath = "D:\\" + oldFileName;
            File file = new File(filePath);
            String fileName = file.getName();
            byte[] tempFileBody = File2byte(file);
            int i = labelOperator.isLabelledFile(tempFileBody);
            if (i > 0) {
                int fileLevel = labelOperator.getFileLevel(tempFileBody);
                //是密标文件，则调用时代宜信的脱标接口
                byte[] removeByte = labelOperator.removeFileLabel("testUser", tempFileBody);
                tempFileBody = removeByte;
            }
            // 调用文件转换服务之前，要把doc脱标成白文件，转换成功后，再对
            if (null != tempFileBody) {
                param.put("bytes", tempFileBody);
            }
            param.put("sourceType", "doc");
            param.put("destType", "ofd");
            JSONObject urlJson = httpPost(servicePath, param);
            if ("success".equals(urlJson.get("returnmsg"))) {
                JSONObject data = (JSONObject) urlJson.get("data");
                String bytes = (String) data.get("bytes");
                byte[] oldFileByte = Base64.getDecoder().decode(bytes);
                short fileFrom = 0;
                //文件密级标志xml
                String labelXml5 = "<secAttrib><secrecy>" + 5 + "</secrecy></secAttrib>";
                byte[] newFileByte5 = labelOperator.bindFileLabel("testUser", oldFileByte, fileName, labelXml5, fileFrom);
                // 输出加标后的文件
                getFile(newFileByte5, "D:\\", newFileName + ".ofd");
            } else {

            }
        } catch (Exception e) {

        }
    }

    /**
     * bfile 需要转换成文件的byte数组
     * filePath  生成的文件保存路径
     * fileName  生成文件后保存的名称如test.pdf，test.jpg等
     */
    public static void getFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            boolean isDir = dir.isDirectory();
            if (!isDir) {
                // 目录不存在则先建目录
                try {
                    dir.mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}
